package remote

import (
	"apedge/pkg/configs"
	"apedge/pkg/protocol"
	"apedge/pkg/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

// 物理节点打标签
func Ks8TagNode(id int64, key, value string) error {
	var respBody protocol.APISuccessRsp

	var client = &http.Client{
		Timeout: time.Second * 10,
	}

	reqContent := protocol.K8sTagNodeReq{
		Key:   key,
		Value: value,
	}
	data, err := json.Marshal(reqContent)
	if err != nil {
		return err
	}
	logger.Infof("tag node req: %s", string(data))

	url := utils.GetHttpUrl(configs.Config.Relevant.Service.APSC, fmt.Sprintf(ApscTagNode, id))
	logger.Infoln("tag node url: ", url)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&respBody)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf("tag node svc error %d %+v", resp.StatusCode, respBody)
	}

	if respBody.Code != 0 {
		return fmt.Errorf("tag node svc error %d %+v", respBody.Code, respBody.Msg)
	}

	logger.Infof("tag node rsp: %+v", respBody)
	return nil
}

// 物理节点打污点
func Ks8TaintNode(id int64, key, value, effect string) error {
	var respBody protocol.APISuccessRsp

	var client = &http.Client{
		Timeout: time.Second * 10,
	}

	reqContent := protocol.K8sTaintNodeReq{
		Key:    key,
		Value:  value,
		Effect: effect,
	}
	data, err := json.Marshal(reqContent)
	if err != nil {
		return err
	}
	logger.Infof("taint node req: %s", string(data))

	url := utils.GetHttpUrl(configs.Config.Relevant.Service.APSC, fmt.Sprintf(ApscTaintNode, id))
	logger.Infoln("taint node url: ", url)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&respBody)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf("taint node svc error %d %+v", resp.StatusCode, respBody)
	}

	if respBody.Code != 0 {
		return fmt.Errorf("taint node svc error %d %+v", respBody.Code, respBody.Msg)
	}

	logger.Infof("taint node rsp: %+v", respBody)
	return nil
}
